package com.freeter.modules.gjs.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.freeter.modules.gjs.entity.StockStatus;
import com.freeter.modules.gjs.entity.User;
import com.freeter.modules.gjs.mapper.StockStatusMapper;
import com.freeter.modules.gjs.mapper.UserMapper;
import com.freeter.modules.gjs.util.SendMailUtil;
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class LowStockAlertComponent {

    @Value("${mail.office365.from}")
    private String mailFrom;
    @Value("${mail.office365.pass}")
    private String mailPass;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StockStatusMapper stockStatusMapper;

    public void sendAlertMail()  {
        // 查询所有有低库存提醒权限的用户（此处简化为所有enabled用户，实际可扩展为角色权限判断）
        Wrapper<User> queryWrapper = new EntityWrapper<>();
        List<User> users = userMapper.selectList(queryWrapper);
        for (User user : users) {
            if (user.getEnabled() != null && user.getEnabled().intValue() == 1 && user.getLogin() != null && user.getLogin().matches("^[\\s]*\\w+([-+.'']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*[\\s]*$")) {
                try {
                    // 查询该用户可见的低库存物品（此处简化为全表，实际可扩展为项目/站点权限）
                    List<StockStatus> stocks = stockStatusMapper.selectLowStock();
                    if (stocks != null && !stocks.isEmpty()) {
                        StringBuilder body = new StringBuilder();
                        for (StockStatus stock : stocks) {
                            body.append(stock.getItemDesc())
                                    .append(" (Project/Site: ")
                                    .append(stock.getProjectCode())
                                    .append(stock.getSiteInfo() != null ? ("-" + stock.getSiteInfo()) : "")
                                    .append(", Qty: ")
                                    .append(stock.getStockQty())
                                    .append(" ")
                                    .append(stock.getUom())
                                    .append(" (")
                                    .append(stock.getLowstockPercentage())
                                    .append(") )<br />");
                        }
                        String subject = "[IMS] Low Stock Alert";
                        SendMailUtil.send365Email(user.getLogin(), subject, body.toString(), mailFrom, mailPass);
                    }
                } catch (MessagingException e) {
                    System.err.println("Low Stock Alert: Failed send mail to " + user.getLogin());
                    e.printStackTrace();
                } catch (Exception e) {
                    System.err.println("Low Stock Alert: An error occurred: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}
